package com.example.myproject.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

public class FilesUtil {


  private static final List<String> allowedExtensions = Arrays.asList("jpg", "jpeg", "png", "txt", "pdf","docx"); // 可根据需要修改

  // 检查文件扩展名是否允许
  public static boolean isExtensionAllowed(String fileName) {
    String fileExtension = getFileExtension(fileName);
    return allowedExtensions.contains(fileExtension);
  }

  // 获取文件扩展名
  public static String getFileExtension(String fileName) {
    int lastIndexOfDot = fileName.lastIndexOf('.');
    if (lastIndexOfDot > 0 && lastIndexOfDot < fileName.length() - 1) {
      return fileName.substring(lastIndexOfDot + 1).toLowerCase();
    }
    return ""; // 返回空字符串表示没有扩展名
  }

  // 下载文件
  public static void downloadFile(File file, HttpServletResponse response) throws IOException {

    if (!file.exists()) {
      throw new IOException("File not found.");
    }
    String fileName = file.getName();
    // 对文件名进行URLEncoder编码
//    String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
    // 打印调试信息

    response.setHeader("Content-Disposition", "attachment; filename=\"" +fileName  + "\"");
    String contentType = getContentType(file);
    response.setContentType(contentType);

    try (FileInputStream fileInputStream = new FileInputStream(file);
         OutputStream outputStream = response.getOutputStream()) {
      byte[] buffer = new byte[4096]; // 增大缓冲区
      int bytesRead;
      while ((bytesRead = fileInputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
      }
      outputStream.flush();
    }
  }

  // 根据文件扩展名获取 Content-Type
  private static String getContentType(File file) {
    String fileName = file.getName();
    if (fileName.endsWith(".txt")) {
      return "text/plain";
    } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
      return "image/jpeg";
    } else if (fileName.endsWith(".png")) {
      return "image/png";
    } else if (fileName.endsWith(".pdf")) {
      return "application/pdf";
    } else if (fileName.endsWith(".doc")) {
      return "application/msword"; // 处理 .doc 文件
    } else if (fileName.endsWith(".docx")) {
      return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; // 处理 .docx 文件
    }
    return "application/octet-stream"; // 默认类型
  }

}
